package com.kintreda.ieco_server.module.api.web;

import com.kintreda.ieco_server.bean.account.User;
import com.kintreda.ieco_server.bean.goods.BangDingSack;
import com.kintreda.ieco_server.bean.goods.Places;
import com.kintreda.ieco_server.bean.goods.Sack;
import com.kintreda.ieco_server.bean.order.BuyRecord;
import com.kintreda.ieco_server.bean.order.UsageRecord;
import com.kintreda.ieco_server.core.web.BaseController;
import com.kintreda.ieco_server.core.web.R;
import com.kintreda.ieco_server.module.account.service.IUserService;
import com.kintreda.ieco_server.module.order.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Created by IntelliJ IDEA
 * @Project_Name ieco_server
 * @Package com.kintreda.ieco_server.module.qrcode.web
 * @Author ZhongYao_H
 * @Date 2019/4/30:10:45
 * @Year 2019 Month 04 Day 30
 * @Date_zh 2019 年 四月 星期二
 */
@Controller
@RequestMapping({"/api/qrcode","/scan"})
public class ApiQrCodeController extends BaseController {

    @Autowired
    IBuyRecordService buyRecordService;
    @Autowired
    IUserService userService;
    @Autowired
    ISackService sackService;
    @Autowired
    IUsageRecordService usageRecordService;
    @Autowired
    IBangDingSackService bangDingSackService;
    @Autowired
    IPlacesService placesService;

    @Value("#{properties['qrcode.prefix']}")
    private String prefix;
    @Value("#{properties['server.domian']}")
    private String doman;
    @Value("#{properties['qrcode.path']}")
    private String resourcsPath;
    @Value("#{properties['scan.qrcode']}")
    private String url;

    /**
     *
     * 扫码
     * @param code
     * @return
     */
    @RequestMapping(value = "/qrcode/ecobag",method = RequestMethod.GET)
    @ResponseBody
    private Object scanCode(String code,String openid,@RequestParam(value = "scantype",defaultValue = "0") String scantype){
        System.out.println(" 扫描成功 code="+code);
        if (scantype.equals("0")){
            try {
                if (openid.equals("")){
                    return R.error("登录失效");
                }
                userService.findUserByOpenId(openid).getId();
            }catch (Exception e){
                return R.error("登录失效");
            }

            // 判断袋子是否还有使用中 如果有 则不
            try{
                String userId  =userService.findUserByOpenId(openid).getId();
                String type  =userService.findUserByOpenId(openid).getType();

                Places places ;
                if (type.equals("2")){
                    places = placesService.getByOrgId(userId,"0");
                }else {
                    places = placesService.getByOrgId(userId,"1");
                }

                if (places==null){
                    places = new Places();
                    if (type.equals("2")){
                        places.setType("0");
                    }else {
                        places.setType("1");
                    }
                    places.setOrgId(userId);
                    placesService.save(places);

                }

                Sack  sack = sackService.getSackByQrCode(code);

                if (sack==null){
                    return R.error("袋子已失效");

                }

                if (sack.getStatus().equals("3")){
                    Integer bigDecimal = Integer.parseInt(places.getNum());
                    bigDecimal = bigDecimal + 1;
                    places.setNum(bigDecimal.toString());
                    placesService.update(places);

                    sack.setStatus("4");
                    sackService.update(sack);

                    BuyRecord buyRecord = new BuyRecord();
                    buyRecord.setSackId(code);
                    buyRecord.setNum("1");
                    buyRecord.setMoney("10");
                    buyRecord.setUserOrOrgId(userId);
                    buyRecordService.save(buyRecord);

                    return R.error("代价卷已生效!您获得一个袋子使用权");
                }else if(sack.getStatus().equals("4")) {
                    return R.error("代金卷已使用过!");
                }


                //购买袋子数量
                Long sackNums = Long.parseLong(places.getNum());

                // 使用中的袋子数量
                Long aLong = usageRecordService.countUse(userId);


                //判断用户购买的袋子是否还有可用的    //如果使用中袋子的数量大于购买的袋子数量 则可用袋子无
                if (aLong>=sackNums){
                    return R.error("可用袋子已使用完!需要购买袋子!");
                }

                if (!sackService.sackIsUsable(code)){
                    return R.error("袋子已在使用中,暂时不可用");
                }

                if (sackService.isUsable(code)) {
                    //告知用户袋子是否可用
                    return R.ok().put("qrcode",code).put("type","0");
                }
                return R.error("袋子暂时不可用");
            }catch (NullPointerException e){
                e.printStackTrace();
                return R.error("系统异常,稍后重试");
            }
        }else {
            //确认收集袋子
            if (sackService.sackIsUsable(code)){
                return R.error("袋子未绑定使用!");
            }
            UsageRecord usageRecord = usageRecordService.getByQrcode(code, "0", "-2");
            if (usageRecordService==null || usageRecord.getStatus().equals("-1")){
                return R.error("袋子未绑定使用!");
            }

            usageRecord.setStatus("2");
            usageRecordService.update(usageRecord);
            return R.ok("确认成功").put("type","1");
        }
    }

    @RequestMapping(value = "/use",method = RequestMethod.POST)
    @ResponseBody
    public Object use(String code,String openid){
        try {
            User user = userService.findUserByOpenId(openid);
            UsageRecord usageRecord = new UsageRecord();
            usageRecord.setUserOrOrgid(user.getId());
            usageRecord.setQrCode(code);
            usageRecord.setStatus("0");


            BangDingSack bangDingSack;
            if (user.getType().equals("2")){
                bangDingSack = bangDingSackService.getByOrgId(user.getId(),"0");
            }else {
                bangDingSack = bangDingSackService.getByOrgId(user.getId(),"1");
            }

            if (bangDingSack == null ){
                bangDingSack = new BangDingSack();
                bangDingSack.setOrgId(user.getId());
                bangDingSack.setNum("0");
                if (user.getType().equals("2")){
                    bangDingSack.setType("0");
                }else {
                    bangDingSack.setType("1");
                }
                bangDingSackService.save(bangDingSack);
            }
            Integer n1 = Integer.parseInt(bangDingSack.getNum());
            bangDingSack.setNum(n1+1+"");
            bangDingSackService.update(bangDingSack);
            //设置袋子为使用中
            Sack sack = sackService.getSackByQrCode(code);
            sack.setStatus("1");
            sackService.saveOrUpdate(sack);
            usageRecordService.save(usageRecord);
            return R.ok("绑定成功");

        }catch (NullPointerException e){
            e.printStackTrace();
            return R.error("绑定失败稍后重试");
        }

    }



}
